/* 
core struct
*/

#ifndef __WRK_CORE_T_H__
#define __WRK_CORE_T_H__

#include "unistd.h"
#include "ae.h"
#include "http_parser.h"
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <luajit.h>
#include <sys/types.h>
#include <stdbool.h>

#define RECVBUF  8192

#define SOCKET_TIMEOUT_MS   2000
#define RECORD_INTERVAL_MS  100

#ifdef __cplusplus  
extern "C" {  
#endif  

extern const char *VERSION;

typedef enum {
    START = 0,
    STOP
}wrk_core_state_t;

typedef struct {
    char  *buffer;
    size_t length;
    char  *cursor;
    size_t size;
} wrk_core_buffer_t;

           
typedef struct {
    uint64_t    connections;
    uint64_t    duration;
    uint64_t    threads;
    uint64_t    timeout;
    uint64_t    pipeline;
    uint64_t    start;
    uint64_t    stop_timestamp;     //停止的时间戳
    enum {
        IDEL, RUNNING
    } wrk_core_task_state;
    bool        delay;
    // bool        dynamic;
    bool        latency;
    char        *host;
    SSL_CTX     *ctx;
    bool        is_force; //强攻模式，忽略读response，连接建立后一起发请求
    uint64_t    max_connection;
    // int         phase_cursor;
    // int         phase_last_cursor; //前一个phase
    uint64_t    last_correct_complete_timestamp; //上次修正统计结果时间点
    uint64_t    last_correct_completes; //已经修正过的请求数
    lua_State   *L;
} wrk_core_config_t;


typedef struct wrk_core_thread_t{
    uint16_t  seq;
    pthread_t thread;
    aeEventLoop *loop;
    struct addrinfo *addr;
    uint64_t connections;
    uint64_t *duration;
    uint64_t complete;
    uint64_t requests;
    uint64_t wbytes; //write bytes
    uint64_t rbytes; //read bytes
    uint64_t start;
    lua_State *L;
    // stats_errors_t err;
    struct wrk_core_connection_t *cs;
} wrk_core_thread_t;

typedef struct wrk_core_phase_t{
    uint32_t    id;
    // uint32_t    threads;
    uint64_t    duration;
    uint64_t    connections;
}wrk_core_phase_t;

typedef struct wrk_core_model_t{
    uint32_t  timeout;
    uint32_t phase_cnt;
    const char*   url;
    wrk_core_phase_t*  phase;
    int phase_cursor;
} wrk_core_model_t;

typedef struct wrk_core_connection_t {
    wrk_core_thread_t *t;
    http_parser parser;
    enum {
        FIELD, VALUE
    } state;
    int fd;
    SSL *ssl;
    bool delayed;
    // bool closed;
    uint64_t start;
    uint64_t rt;
    char *request;
    char *request_method;
    size_t request_length;
    size_t written;
    uint64_t pending;
    uint64_t pipeline;
    wrk_core_buffer_t request_path;
    wrk_core_buffer_t request_headers;
    wrk_core_buffer_t request_body;
    wrk_core_buffer_t resp_headers;
    wrk_core_buffer_t resp_body;
    lua_State *L;  //用来存附加数据 add 20200211
    char buf[RECVBUF];
} wrk_core_connection_t;


#ifdef __cplusplus  
}
#endif  

#endif